#include <stdio.h>
#include <stdlib.h>

#define FALSE 0
#define TRUE 1
#define OVERFLOW 2

typedef int Status;
typedef int ElemType;

typedef struct LNode {
    ElemType data;
    struct LNode *next;
} LNode, *LinkedList;

Status InitList(LinkedList *list) {
    *list = (LinkedList) malloc(sizeof(LNode));
    if (!(*list)) {
        printf("OVERFLOW!!!\n");
        return OVERFLOW;
    }
    (*list)->next = (LNode *) NULL;
    return TRUE;
}

Status InsertElem(LinkedList list, int location, ElemType elem) {
    LNode *p = list;
    int i = 0;  //下一个节点是第几个节点
    while (i <= location - 1) {
        p = p->next;
        i++;
    }
    LNode *q = (LNode *) malloc(sizeof(LNode));
    q->data = elem;
    q->next = p->next;
    p->next = q;
    return TRUE;
}

Status DeleteElem(LinkedList list, int location, ElemType *elem){
    LNode *q = list;
    LNode *p;
    int j = 0;
    while (j <= location-1) {
        if(!q){
            return FALSE;
        }
        q = q->next;
        j++;
    }
    p = q->next;
    *elem = q->next->data;
    q->next = q->next->next;
    free(p);
    return TRUE;
}

Status GetElem(LinkedList list, int location, ElemType *elem) {
    LNode *p = list;
    int i = 0;
    while(i <= location){
        if(!p){
            return FALSE;
        }
        p = p->next;
        i++;
    }
    *elem = p->data;
    return TRUE;
}

void PrintList(LinkedList list) {
    printf("Print List >>> \n");
    LNode *p = list->next;
    while (p) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

int ListLength(LinkedList list){
    LNode *p = list->next;
    int i = 0;
    while(p){
        i++;
        p = p->next;
    }
    return i;
}

Status isListEmpty(LinkedList list){
    LNode *p = list->next;
    if(p){
        return FALSE;
    }
    return TRUE;
}

void LocateElem(LinkedList list, ElemType elem, int *location){
    LNode *p = list->next;
    int i = 1;
    while(p){
        if(p->data == elem){
            *location = i;
        }
        p = p->next;
        i++;
    }
}

int main() {
    LinkedList list;
    InitList(&list);
    InsertElem(list, 0, 1);
    InsertElem(list, 1, 2);
    InsertElem(list, 2, 3);
    InsertElem(list, 1, 4);
    InsertElem(list, 1, 5);
    PrintList(list);
    DeleteElem(list, 2);
    PrintList(list);
    int a;
    GetElem(list, 2, &a);
    printf("%d \n", a);
    int b;
    ListLength(list,&b);
    printf("%d \n", b);
    int c;
    LocateElem(list, 5, &c);
    printf("%d \n", c);
    // PrintList(list);
    return 0;
}